<template>
  <!--  添加按钮-->
  <div class="tools-div">
    <el-button type="success" size="small" @click="addShow">添 加</el-button>
  </div>
  <!--  添加修改的对话框-->
  <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
    <el-form label-width="120px">
      <el-form-item label="规格名称">
        <el-input v-model="productSpec.specName"/>
      </el-form-item>
      <el-form-item>
        <el-button size="default" type="success" @click="addSpec">
          添加新规格
        </el-button>
      </el-form-item>
      <el-form-item label="" v-for="(item , index) in productSpec.specValue" :key="index">
        <el-row>
          <el-col :span="10">
            <el-input
                v-model="item.key"
                placeholder="规格"
                style="width: 90%;"
            />
          </el-col>
          <el-col :span="10">
            <el-input
                v-model="item.valueList"
                placeholder="规格值(如:白色,红色)"
                style="width: 90%;"
            />
          </el-col>
          <el-col :span="4">
            <el-button size="default" type="danger" @click="delSpec(index)">删除</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item align="right">
        <el-button type="primary" @click="saveOrUpdate">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!--  数据展示表格-->
  <el-table :data="list" style="width: 100%">
    <el-table-column prop="specName" label="规格名称"/>
    <el-table-column label="规格值" #default="scope">
      <div
          v-for="(item1, index1) in scope.row.specValue"
          :key="index1"
          style="padding: 5px; margin: 0;width: 100%;"
      >
        {{ item1.key }}：
        <span
            v-for="(item2, index2) in item1.valueList"
            :key="index2"
            class="div-atrr"
        >
            {{ item2 }}
            </span>
      </div>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间"/>
    <el-table-column label="操作" align="center" width="200" #default="scope">
      <el-button type="primary" size="small" @click="editShow(scope.row)">
        修改
      </el-button>
      <el-button type="danger" size="small" @click="remove(scope.row.id)">
        删除
      </el-button>
    </el-table-column>
  </el-table>

  <!--  分页条-->
  <el-pagination
      v-model:current-page="pageParams.page"
      v-model:page-size="pageParams.limit"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />


</template>

<script setup>
import {ref, onMounted} from 'vue'
import {getData, save, update, deleteById} from '@/api/productSpec'
import {ElMessage, ElMessageBox} from 'element-plus'
// 删除
const remove = (id) => {
  ElMessageBox.confirm(
      '确定要删除吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
  ).then(async () => {
    const {code} = await deleteById(id)
    //刷新数据
    if (code === 200) {
      ElMessage.success("删除成功")
      fetchData()
    }
  })
      .catch(() => {
        ElMessage.info("取消成功")
      })

}
//修改对话框
const editShow = async (row) => {
  //显示修改对话框
  dialogVisible.value = true
  //数据回显示
  productSpec.value = row
}
//  修改功能实现
const edit = async () => {
  //拿到克隆的对象
  const cloneSpec = JSON.parse(JSON.stringify(productSpec.value));
  console.log(cloneSpec)
  /**
   * {
   *     "id": 12,
   *     "createTime": "2025-03-11 04:10:00",
   *     "updateTime": "2025-03-11 04:10:00",
   *     "isDeleted": 0,
   *     "specName": "测试3",
   *     "specValue": [
   *         {
   *             "key": "颜色",
   *             "valueList": [
   *                 "红色",
   *                 "白色"
   *             ]
   *         },
   *         {
   *             "key": "小大",
   *             "valueList": "M,S"   // 不是数组需要转换
   *         }
   *     ]
   * }
   */
  cloneSpec.specValue.forEach(item => {
    if (typeof item.valueList === "string") {
      //如果是字符串就转换为数组
      item.valueList = item.valueList.split(",")
    }
  })


  // console.log(cloneSpec)
  cloneSpec.specValue = JSON.stringify(cloneSpec.specValue)
  console.log(cloneSpec)


  const {code} = await update(cloneSpec)
  if (code === 200) {
    ElMessage.success("修改成功")
    //关闭对话框
    dialogVisible.value = false
    //刷新数据
    fetchData()
  }
  /**
   * {
   *     "id": 2,
   *     "createTime": "2023-05-06 04:56:08",
   *     "updateTime": "2023-05-25 06:59:59",
   *     "isDeleted": 0,
   *     "specName": "笔记本电脑",
   *     "specValue": [
   *         {
   *             "key": "内存",
   *             "valueList": [
   *                 "8G",
   *                 "16G",
   *                 "32G"
   *             ]
   *         }
   *     ]
   * }
   * {
   *     "id": 2,
   *     "createTime": "2023-05-06 04:56:08",
   *     "updateTime": "2023-05-25 06:59:59",
   *     "isDeleted": 0,
   *     "specName": "笔记本电脑",
   *     "specValue": [
   *         {
   *             "key": "内存",
   *             "valueList": [
   *                 "8G",
   *                 "16G",
   *                 "32G"
   *             ]
   *         }
   *     ]
   * }
   */

}
// 更新或者修改提交的按钮
const saveOrUpdate = () => {
  //有id是修改,没id是提交
  if (productSpec.value.id) {
    //有id修改
    edit()
  } else {
    //新增
    add()
  }
}
//封装新增方法
const add = async () => {

  // 为了不对双向绑定的前端视图产生影响,这里采用对象克隆,  把克隆的对象存储到数据库
  const specClone = JSON.parse(JSON.stringify(productSpec.value));
  // 数据库要的格式 ,需要转换
  //[{"key":"颜色","valueList":["白色","红色","黑色"]},{"key":"内存","valueList":["8G","18G"]}]

  // console.log(specClone);
  //输出的内容
  /**
   * {
   *     "id": "",
   *     "specName": "测试",
   *     "specValue": [
   *         {
   *             "key": "1",
   *             "valueList": "1,2,3"   // 要对valueList进行处理,转化为送数组,而不是逗号分割
   *         },
   *         {
   *             "key": "2",
   *             "valueList": "3,4,5"
   *         }
   *     ]
   * }
   */
  specClone.specValue.forEach(item => {
    item.valueList = item.valueList.split(",")
  })
  // console.log(specClone)
  /** 把 valueList成功的转化为数组, 下一步把SpecValue转化为字符串即可
   * {
   *     "id": "",
   *     "specName": "",
   *     "specValue": [
   *         {
   *             "key": "1",
   *             "valueList": [
   *                 "1",
   *                 "2",
   *                 "3"
   *             ]
   *         },
   *         {
   *             "key": "2",
   *             "valueList": [
   *                 "3",
   *                 "4",
   *                 "5"
   *             ]
   *         }
   *     ]
   * }
   */
  specClone.specValue = JSON.stringify(specClone.specValue)

  // console.log(specClone)
  /**
   {
   "id": "",
   "specName": "",
   "specValue": "[{\"key\":\"1\",\"valueList\":[\"1\",\"2\",\"3\"]},{\"key\":\"2\",\"valueList\":[\"3\",\"4\",\"5\"]}]"
   }
   */


  const {code} = await save(specClone)
  if (code === 200) {
    ElMessage.success("新增成功")
    //关闭对话框
    dialogVisible.value = false
    //刷新数据
    fetchData()
  }
}
// 删除指定索引的规格
const delSpec = index => {
  // console.log(index)
  //   splice(指定索引开始,删除的个数)
  productSpec.value.specValue.splice(index, 1)
}
// 添加新规格
const addSpec = () => {
  // 添加一个空的遍历项, 就多了一行
  productSpec.value.specValue.push({})
}
// 添加数据模型显示
const defaultFormParams = {
  id: '',
  specName: '',
  specValue: [{
    key: '',
  }
  ]
}
const productSpec = ref(defaultFormParams)
//控制 添加或者修改对话框的显示
const dialogVisible = ref(false)
//添加对话框展示
const addShow = () => {
  // //清空模型,防止干咯
  //  productSpec.value=defaultFormParams
  //显示对话框
  dialogVisible.value = true
}
onMounted(() => {
  fetchData()
})
// 表格数据模型
const list = ref([])

// 分页条数据模型
const total = ref(0)

const fetchData = async () => {
  //发请求拿数据
  const {data} = await getData(pageParams.value.page, pageParams.value.limit)
  /**
   * "list": [
   *             {
   *                 "id": 8,
   *                 "createTime": "2023-07-19 01:41:16",
   *                 "updateTime": "2023-07-19 01:41:24",
   *                 "isDeleted": 0,
   *                 "specName": "冰箱",
   *                 "specValue": "[{\"key\":\"高度\",\"valueList\":[\"200\"]},{\"key\":\"容积\",\"valueList\":[\"60L\"]}]"
   *             }
   *             ]
   *             拿到的数据 specValue需要转换为对象,才能正常 点出属性
   */
  // 开始转换,，specValue 就变成了一个 真正的数组，可以直接用 v-for 进行遍历。
  data.list.forEach(item => {
    item.specValue = JSON.parse(item.specValue)
  })
  list.value = data.list
  total.value = data.total

}
// 页数发生改变
const handleCurrentChange = () => {
  fetchData()
}
//页的大小发生改变
const handleSizeChange = () => {
  fetchData()
}
//定义分页数据模型
const defaultPageFrom = {
  page: 1,
  limit: 10
}
const pageParams = ref(defaultPageFrom)

</script>


<style scoped>
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.div-atrr {
  padding: 5px 10px;
  margin: 0 10px;
  background-color: powderblue;
  border-radius: 10px;
}

</style>